package org.example.common.security.service;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.common.core.constants.CacheConstants;
import org.example.common.core.constants.JwtConstants;
import org.example.common.redis.service.RedisService;
import org.example.common.core.domain.LoginUser;
import org.example.common.core.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 操作用户登录 token 的方法
 */
@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken (Long userId, String secret, Integer identity, String nickName, String headImage) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        String token = JwtUtils.createToken(claims, secret);

        // 存入 redis
        String key = getTokenKey(String.valueOf(userId));
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(key, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);

        return token;
    }

    public void extendToken(Claims claims) {
        String userId = getUserId(claims);
        if (userId == null) return;
        String key = getTokenKey(userId);

        Long expire = redisService.getExpire(key, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(key, CacheConstants.EXP, TimeUnit.MINUTES);
        }

    }

    public LoginUser getLoginUser(String token, String secret) {
        String userId = getUserId(token, secret);
        if (userId == null) return null;
        return redisService.getCacheObject(getTokenKey(userId), LoginUser.class);
    }

    public boolean deleteLoginUser(String token, String secret) {
        String userId = getUserId(token, secret);
        if (userId == null) return false;
        return redisService.deleteObject(getTokenKey(userId));
    }

    public String getUserId(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserId(claims);
    }

    public String getUserId(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserId(claims); //获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token: {}出现异常，", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token: {}出现异常，", token, e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName, String headImage, String userId) {
        String tokenKey = getTokenKey(userId);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }


    private String getTokenKey(String userId) {
        return CacheConstants.LOGIN_TOKEN_KEY + userId;
    }
}
